import { ref , onMounted } from "vue"
import type {Query} from "@/interface/Query";
import type {Repair} from "@/interface/Repair";
import type {TableColumnsType} from "ant-design-vue";
import {listApi, assignApi, removeApi , changeStatusApi } from "@/controller/RepairApi";
import type { SendOrdersVo } from "@/interface/SendOrdersVo";
import type {Rule} from "ant-design-vue/es/form";
import type { User } from "@/interface/User"

import { repairWorkerApi } from "@/controller/UserApi";
import {message} from "ant-design-vue";


export default function () {

    let queryModel = ref({
        page: 1,
        size: 15,
        keyWord: ''
    } as Query);

    let searchBox = ref<boolean>(true);

    onMounted(()=> {
        list();
    });

    function resetQuery() {
        queryModel.value = {
            page: 1,
            size: 15,
            keyWord: ''
        } as Query;
        list();
    }

    let data = ref<Repair[]>([]);
    let total = ref<number>(0);
    function list() {
        listApi(queryModel.value).then(res => {
            if(res.code == 200) {
                data.value = res.data.records;
                total.value = parseInt(res.data.totalRow);
            }
        });
    }

    let infoStore = ref({
        open: false,
        info : {} as Repair,
        user: {} as User,
        worker: {} as User
    })


    function info(data : Repair) {
        infoStore.value.open = true;
        infoStore.value.info = data;
        if (infoStore.value.info.house && infoStore.value.info.house.users && infoStore.value.info.house.users.length > 0) {
            infoStore.value.user = infoStore.value.info.house.users.find(item => item.id === infoStore.value.info.userId) as User;
            if(infoStore.value.info.maintenanceStaffId) {
                infoStore.value.worker = infoStore.value.info.house.users.find(item => item.id === infoStore.value.info.maintenanceStaffId) as User;
            }
        }
    }

    let orderRules : Record<string, Rule[]>  = {
        userId: [{ required: true, message: '请选择维修人员', trigger: 'blur' }],
    }

    let columns = ref<TableColumnsType>([
        {
            title: '楼宇名称',
            dataIndex: 'floorName',
            width: 100,
            resizable: true,
            fixed: 'left',
            align: 'center'
        },
        {
            title: '单元号',
            dataIndex: 'unitNumber',
            width: 100,
            resizable: true,
            align: 'center'
        },
        {
            title: '楼层',
            dataIndex: 'floor',
            width: 70,
            resizable: true,
            align: 'center'
        },
        {
            title: '房间号',
            dataIndex: 'building',
            width: 120,
            resizable: true,
            align: 'center'
        },
        {
            title: '问题类型',
            dataIndex: 'problemType',
            width: 160,
            resizable: true,
            align: 'center'
        },
        {
            title: '问题描述',
            dataIndex: 'problemDescription',
            width: 160,
            resizable: true,
            align: 'center'
        },
        {
            title: '附件',
            dataIndex: 'attachmentUrl',
            width: 160,
            resizable: true,
            align: 'center'
        },
        {
            title: '状态',
            dataIndex: 'status',
            width: 160,
            resizable: true,
            align: 'center'
        },
        {
            title: '备注',
            dataIndex: 'remark',
            width: 160,
            resizable: true,
            align: 'center'
        },
        {
            title: '上报时间',
            dataIndex: 'reportTime',
            width: 160,
            resizable: true,
            align: 'center'
        },
        {
            title: '处理时间',
            dataIndex: 'completionTime',
            width: 160,
            resizable: true,
            align: 'center'
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 300,
            resizable: true,
            fixed: 'right',
            align: 'center'
        }
    ])

    function pageChange(page : number ,size : number) {
        queryModel.value.page = page;
        queryModel.value.size = size;
        list();
    }

    let rowsData  = ref<Repair[]>([])
    function selectData(selectedRowKeys : any, selectedRows : Repair[]) {
        rowsData.value = selectedRows;
    }

    let orderRef = ref();

    function resetSendOrders() {
        sendOrdersStore.value.open = false;
        sendOrdersStore.value.order = {} as SendOrdersVo;
    }

    function handleResizeColumn(w : any, col : any) {
        col.width = w;
    }

    let sendOrdersStore = ref({
        open: false,
        order: {} as SendOrdersVo,
        user: [] as User[]
    });

    function sendOrders(data : SendOrdersVo) {
        repairWorkerApi().then(res => {
            if(res.code == 200) {
                sendOrdersStore.value.user = res.data;
            }
        });
        sendOrdersStore.value.open = true;
        sendOrdersStore.value.order = data;
    }

    function sendOrdersOk() {
        orderRef.value.validate().then((valid : any) => {
            assignApi(sendOrdersStore.value.order).then(res =>{
                if(res.code == 200) {
                    list();
                    resetSendOrders();
                    message.success('维修师傅安排成功');
                }else {
                    message.error(res.msg);
                }
            });
        }).catch((err : any) => {
            console.log(err);
        });
    }

    function remove(ids ? : string[]) {
        if (ids && ids.length > 0) {
            removeApi(ids).then(res => {
                if(res.code == 200) {
                    list();
                    message.success('删除成功');
                }else {
                    message.error(res.msg);
                }
            });
        }else {
            remove(rowsData.value.map(item => item.id));
        }
    }


    let changeStatusFrom = ref();
    let changeStatusStore = ref({
        open: false,
        status: 0,
        info: {} as Repair,
        user: [] as User[],
        rules: {
            remark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
            status: [{ required: true, message: '请选择状态', trigger: 'blur' }]
        },
    })


    function changeStatus(id : string,status : number) {
        changeStatusStore.value.info.id = id;
        repairWorkerApi().then(res => {
            if(res.code == 200) {
                changeStatusStore.value.user = res.data;
            }
        });
        changeStatusStore.value.status = status;
        changeStatusStore.value.open = true;
    }

    function resetChangeStatus() {
        changeStatusStore.value.open = false;
        changeStatusStore.value.info = {} as Repair;
    }

    function changeStatusOk() {
        changeStatusFrom.value.validate().then((valid : any) => {
            changeStatusApi(changeStatusStore.value.info).then(res => {
                if(res.code == 200) {
                    list();
                    resetChangeStatus();
                    message.success('状态修改成功');
                }else {
                    message.error(res.msg);
                }
            });
        }).catch((err : any) => {
            console.log(err);
        });
    }

    return {
        searchBox , queryModel , list , resetQuery ,
        columns , data , total , pageChange , handleResizeColumn ,
        sendOrdersStore, sendOrders, sendOrdersOk , orderRules ,
        orderRef , resetSendOrders , info , infoStore , remove ,
        selectData , rowsData , changeStatus , changeStatusStore ,
        changeStatusFrom , resetChangeStatus , changeStatusOk
    }
}
